package com.yssw.client.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.yssw.client.domain.vo.WeChatPaymentVO;
import com.yssw.client.service.WeChatPaymentService;
import com.yssw.common.utils.uuid.UUID;
import com.yssw.config.WeChatPaymentConfig;
import com.yssw.util.WxpayV3Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author KnockingFarmers
 * @Date 2023/4/1 17:16
 * @PackageName:com.yssw.client.service.impl
 * @ClassName: WeChatPaymentServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Service
public class WeChatPaymentServiceImpl implements WeChatPaymentService {

    @Autowired
    private WeChatPaymentConfig paymentConfig;

    //支付参数  名称 价格 openid
    private  JSONObject param(WeChatPaymentVO weChatPaymentVO) {
        //外部订单号
        String payOrderId = String.valueOf(UUID.randomUUID()).trim().replaceAll("-","").toUpperCase().substring(0, 16);

        // 微信统一下单请求对象
        JSONObject reqJSON = new JSONObject();
        reqJSON.put("out_trade_no", payOrderId);
        reqJSON.put("description", weChatPaymentVO.getDescription());
        // 订单失效时间，遵循rfc3339标准格式，格式为yyyy-MM-DDTHH:mm:ss+TIMEZONE,示例值：2018-06-08T10:34:56+08:00
//        reqJSON.put("time_expire", String.format("%sT%s+08:00", DateUtil.format(orderPay.getExpiredTime(), DatePattern.NORM_DATE_FORMAT), DateUtil.format(orderPay.getExpiredTime(), DatePattern.NORM_TIME_FORMAT)));

        reqJSON.put("notify_url", "https://www.baidu.com");
        JSONObject amount = new JSONObject();
        amount.put("total", weChatPaymentVO.getTotal());
        amount.put("currency", "CNY");
        reqJSON.put("amount", amount);
        //获取本机的ip地址
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        JSONObject sceneInfo = new JSONObject();
        sceneInfo.put("payer_client_ip", addr.getHostAddress());
        reqJSON.put("scene_info", sceneInfo);
        reqJSON.put("appid", paymentConfig.getAppId());
        reqJSON.put("mchid", paymentConfig.getMchId());
        //reqJSON.put("trade_type", "JSAPI");
        JSONObject payer = new JSONObject();
        payer.put("openid", weChatPaymentVO.getOpenid());
        reqJSON.put("payer", payer);
        System.out.println(reqJSON);
        return reqJSON;
    }

    /**
     * 保存微信支付订单数据
     * @return
     */
    public boolean saveWeChatPayment(){
        return true;
    }


    @Override
    public JSONObject payment(WeChatPaymentVO weChatPaymentVO) {
        //配置微信支付商家信息
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setMchId(paymentConfig.getMchId());
        wxPayConfig.setAppId(paymentConfig.getAppId());
        wxPayConfig.setMchKey(paymentConfig.getMchKey());
        wxPayConfig.setApiV3Key(paymentConfig.getApiV3key());
        wxPayConfig.setCertSerialNo(paymentConfig.getMerchantSerialNumber());
        wxPayConfig.setKeyPath(paymentConfig.getKeyPath());
        wxPayConfig.setPrivateCertPath(paymentConfig.getPrivateCertPath());
        wxPayConfig.setPrivateKeyPath(paymentConfig.getPrivateKeyPath());

        // 小程序支付
        wxPayConfig.setTradeType(WxPayConstants.TradeType.JSAPI);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig); //微信配置信息

        // 官方接口文档地址- https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_1_1.shtml
        String url = "/v3/pay/transactions/jsapi";
        JSONObject jsonObject = null;
        try {
            jsonObject= WxpayV3Util.unifiedOrderV3(url, param(weChatPaymentVO), wxPayService);
            log.info("支付返回：{}", jsonObject);
        } catch (WxPayException e) {
            e.printStackTrace();
        }

        //商户号
        jsonObject.put("partnerid",paymentConfig.getMerchantId());
        return jsonObject;
    }
}
